package com.infocollect.framework.security.service;

import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.infocollect.common.constant.Constants;
import com.infocollect.common.exception.CustomException;
import com.infocollect.common.exception.user.CaptchaException;
import com.infocollect.common.exception.user.CaptchaExpireException;
import com.infocollect.common.exception.user.UserPasswordNotMatchException;
import com.infocollect.common.utils.MessageUtils;
import com.infocollect.framework.manager.AsyncManager;
import com.infocollect.framework.manager.factory.AsyncFactory;
import com.infocollect.framework.redis.RedisCache;
import com.infocollect.framework.security.LoginUser;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 登录校验方法
 *
 * @author dongpj
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    private static final String PASSWORD_RETRY_CACHE="password_retry_cache:";

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        if (isOverLimit(username, 5)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "登陆失败次数过多，请过5分钟重试"));
//            throw new UserPasswordNotMatchException();
            throw new CustomException("登陆失败次数过多，请过5分钟重试");
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        remove(username);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 是否超过限制
     */
    public boolean isOverLimit(String username, Integer limit) {
        //设置次数
        AtomicInteger retryCount = limitCacheGet(username);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
        }
        if (retryCount.incrementAndGet() > limit) {
            //重试次数如果大于限制次数，就锁定
            return true;
        }
        //并将其保存到缓存中(有效时长5分)
        limtCachePut(username, retryCount, 300L);
        return false;
    }
    /**
     * 登录成功时，清除
     */
    public void remove(String userName) {
        redisCache.deleteObject(PASSWORD_RETRY_CACHE+userName);
    }

    private void limtCachePut(String userName, AtomicInteger retryNum, Long expire) {
//        redisCache.setEx(PASSWORD_RETRY_CACHE+userName, retryNum,expire);
        redisCache.setCacheObject(PASSWORD_RETRY_CACHE+userName, retryNum);
        redisCache.expire(PASSWORD_RETRY_CACHE+userName,expire, TimeUnit.SECONDS);
    }

    private  AtomicInteger limitCacheGet(String userName) {
        Integer retryNum = redisCache.getCacheObject(PASSWORD_RETRY_CACHE + userName);
        if(retryNum==null){
            return new AtomicInteger(0);
        }else {
            return new AtomicInteger(retryNum);
        }
    }
}
